package org.opsliframework.boot.Controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.opsliframework.boot.oss.FileAttr;
import org.opsliframework.boot.oss.conf.LocalConfig;
import org.opsliframework.boot.oss.conf.StorageType;
import org.opsliframework.boot.oss.service.LocalService;
import org.opsliframework.boot.oss.tool.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;


/**
 * 文件管理 Controller
 *
 * @author Parker
 * @date 2020-09-13 17:40
 */
@Api(tags = "文件管理类")
@Slf4j
@RestController()
@RequestMapping("/oss")
public class OssRestController {

    /**
     * 文件上传
     * @param request 文件流 request
     * @return ResultWrapper
     */
    @Autowired
    LocalConfig config;
    @Autowired
    private StorageType storageTypeYaml;

    @Autowired
    LocalService localService;
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping("/upload")
    public R<?> upload(MultipartHttpServletRequest request) {
        log.info("文件上传开始");
        Iterator<String> itr = request.getFileNames();
        String uploadedFile = itr.next();
        List<MultipartFile> files = request.getFiles(uploadedFile);

        //自定义路径
        if (request.getParameter("type") != null&&request.getParameter("type").length()>0) {
            config.setCustomPath(request.getParameter("type"));
        }
        if (CollectionUtils.isEmpty(files)) {
            // 请选择文件
            return R.fail(20310,"请选择文件");
        }

        try {
            MultipartFile multipartFile = files.get(0);
            Resource resource = multipartFile.getResource();
            String filename = resource.getFilename();
            log.info("存储方式：{}", storageTypeYaml.getType());
            log.info("本地配置{}",config);
            // 调用OSS 服务保存文件
            FileAttr fileAttr = localService.upload(multipartFile.getInputStream(), FileUtil.extName(filename),config);
            return R.ok(fileAttr);
        }catch (IOException e){
            log.error(e.getMessage(), e);
        }
        return R.fail();
    }
}